<template>
    <view class="authorization-page">
        <!-- 协议 -->
        <div class="flex flex-nowrap radio-group">
            <van-checkbox :value="agreeAgreement" shape="square" @change="onAgreeAgreement"></van-checkbox>
            <label>
                <text>阅读并同意以下</text>
                <text class="agreement">《服务协议》</text>
            </label>
        </div>
        <!--  -->
        <button
            class="login-button"
            :class="{'disabled-button': !agreeAgreement}"
            open-type="getUserInfo"
            @getuserinfo="bindGetUserInfo"
        >微信登录</button>
    </view>
</template>

<script>
export default {
    data() {
        return {
            agreeAgreement: false
        };
    },
    onLoad(options) {},
    onShow() {},
    onunLoad(){
        this.agreeAgreement = false;
    },
    components: {
        uniNavBar
    },
    methods: {
        //
        bindGetUserInfo(e) {
            if (this.agreeAgreement) {
                mpvue.clearStorageSync();
                if (e.mp.detail.userInfo) {
                    let openID = mpvue.getStorageSync("schoolOpenId");
                    if (openID) {
                        console.log(">>>>>>>OPENID: ", openID);
                        // 授权登录
                        this.authorizedLogin(openID);
                    } else {
                        console.log(">>>>>>> 未从缓存拿到OPENID...");
                        // 微信登录
                        this.weChatLogin();
                    }
                } else {
                    wx.showToast({
                        title: "本程序需要您的同意并授权才能登录哦!",
                        icon: "none"
                    });
                }
            } else {
                wx.showToast({
                    title: "请同意服务协议！",
                    icon: "none"
                });
            }
        },
        /**
         * 授权登录
         */
        authorizedLogin(openId) {
            // 判断openId 是否合法
            if (openId === undefined && openId === "") {
                mpvue.showToast({
                    title: "获取openId失败"
                });
                return false;
            }
            mpvue.showLoading({
                title: "正在登录..."
            });
            let _config = {
                headers: {
                    isToken: false,
                    //"TENANT-ID": 10000,
                    "content-type": "application/x-www-form-urlencoded",
                    Authorization:
                        "Basic dXBtczpoM2tyWGZvS1FxRmJpQzZLbE1uZWZGSHU0OUxmMjlOeQ=="
                }
            };
            let _data = {
                mobile: "WX@" + openId
            };
            this.$http
                .post(this.$api.postAuthorized, _data, _config)
                .then(res => {
                    // 如果拿到令牌
                    if (res && res.access_token) {
                        console.log(">>>>>>> access_token:", res.access_token);
                        // 缓存令牌
                        mpvue.setStorageSync("access_token", res.access_token); //将access_token存入本地缓存
                        this.handleGetUserInfo();
                    } else {
                        // 未拿到令牌
                        mpvue.clearStorageSync();
                        mpvue.showModal({
                            content: "登录失败请重试",
                            title: "错误",
                            showCancel: false
                        });
                    }
                })
                .catch(() => {
                    wx.showToast({
                        title: "登录失败，请用账号密码登录！",
                        icon: "none",
                        duration: 2000,
                        mask: true
                    });
                    setTimeout(() => {
                        this.goUPLogin();
                    }, 1500);
                });
        },
        /**
         * 处理程序_获取用户信息
         */
        handleGetUserInfo() {
            // 获取用户信息
            this.$http.get(this.$api.getUserInfo).then(res => {
                console.log(">>>>>>> 用户信息: ", res);

                // 缓存用户信息
                mpvue.setStorageSync("userInfo", res.user);
                // 缓存租户编号
                mpvue.setStorageSync("tenantId", res.user.tenantId);

                mpvue.switchTab({
                    url: "/pages/indexPages/main"
                });
                // 执行绑定OPENID 处理程序
                // this.handleBindOpenID();
            });
        },
        /**
         * 微信登录获取OPENID
         */
        weChatLogin() {
            wx.login({
                success: ({ code }) => {
                    if (code) {
                        // 这里可以把code传给后台，后台用此获取openid及session_key
                        this.$http
                            .get(this.$api.getOpenId, { code })
                            .then(data => {
                                mpvue.setStorageSync(
                                    "schoolOpenId",
                                    data.openid
                                );
                                this.authorizedLogin(data.openid);
                            });
                    }
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
</style>